<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${pageTitle ?: '同步平台 - 数据库恢复'}">同步平台 - 数据库恢复</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar Navigation -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/}">
                                <i class="bi bi-house"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/dashboard}">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/server}">
                                <i class="bi bi-server"></i> 服务器管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/database}">
                                <i class="bi bi-database"></i> 数据库管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/database}">
                                <i class="bi bi-arrow-left-right"></i> 数据库同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/file}">
                                <i class="bi bi-files"></i> 文件同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" th:href="@{/restore}">
                                <i class="bi bi-arrow-counterclockwise"></i> 数据库恢复
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/task/log}">
                                <i class="bi bi-list-check"></i> 同步日志
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">数据库恢复</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#uploadBackupModal">
                            <i class="bi bi-upload"></i> 上传备份文件
                        </button>
                        <a th:href="@{/restore/new}" class="btn btn-sm btn-outline-secondary ms-2">
                            <i class="bi bi-plus-circle"></i> 新建恢复任务
                        </a>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert" style="display: none;">
                    <span id="successMessage"></span>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                
                <div class="alert alert-danger alert-dismissible fade show" role="alert" id="errorAlert" style="display: none;">
                    <span id="errorMessage"></span>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                
                <!-- Restore Tasks Table -->
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>名称</th>
                                <th>目标数据库</th>
                                <th>备份文件</th>
                                <th>最后执行时间</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="taskList">
                            <tr th:if="${tasks.isEmpty()}">
                                <td colspan="7" class="text-center">暂无数据库恢复任务</td>
                            </tr>
                            <tr th:each="task : ${tasks}">
                                <td th:text="${task.id}"></td>
                                <td th:text="${task.name}"></td>
                                <td th:text="${databaseMap[task.databaseId]?.name}"></td>
                                <td th:text="${task.originalFileName}"></td>
                                <td th:text="${task.lastExecutionTime != null ? #temporals.format(task.lastExecutionTime, 'yyyy-MM-dd HH:mm:ss') : '未执行'}"></td>
                                <td>
                                    <span th:if="${task.status == 1}" class="badge bg-success">启用</span>
                                    <span th:if="${task.status == 0}" class="badge bg-secondary">禁用</span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary execute-btn" 
                                            th:data-id="${task.id}" 
                                            th:data-name="${task.name}">
                                        <i class="bi bi-play-fill"></i> 执行
                                    </button>
                                    <a th:href="@{/restore/edit/{id}(id=${task.id})}" class="btn btn-sm btn-outline-secondary">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </a>
                                    <button class="btn btn-sm btn-outline-danger delete-btn" 
                                            th:data-id="${task.id}" 
                                            th:data-name="${task.name}">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    </div>

    <!-- Upload Backup Modal -->
    <div class="modal fade" id="uploadBackupModal" tabindex="-1" aria-labelledby="uploadBackupModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="uploadBackupModalLabel">上传备份文件</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="uploadForm" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="backupFile" class="form-label">备份文件</label>
                            <input type="file" class="form-control" id="backupFile" name="file" accept=".sql,.dump,.backup" required>
                            <div class="form-text">支持SQL文件、数据库备份文件等</div>
                        </div>
                        <div class="mb-3">
                            <label for="targetDatabase" class="form-label">目标数据库</label>
                            <select class="form-select" id="targetDatabase" name="databaseId" required>
                                <option value="">选择目标数据库</option>
                                <option th:each="db : ${databases}" 
                                        th:value="${db.id}" 
                                        th:text="${db.name}"></option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="taskName" class="form-label">任务名称</label>
                            <input type="text" class="form-control" id="taskName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="taskDescription" class="form-label">任务描述</label>
                            <textarea class="form-control" id="taskDescription" name="description" rows="3"></textarea>
                        </div>
                    </form>
                    <div class="progress d-none" id="uploadProgress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="uploadButton">上传</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Execution Confirmation Modal -->
    <div class="modal fade" id="executeConfirmModal" tabindex="-1" aria-labelledby="executeConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="executeConfirmModalLabel">确认执行恢复任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要执行恢复任务 "<span id="executeTaskName"></span>" 吗？</p>
                    <p class="text-danger"><strong>警告：此操作将覆盖目标数据库的数据，请确保已经备份重要数据！</strong></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmExecute">确认执行</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Execution Result Modal -->
    <div class="modal fade" id="executeResultModal" tabindex="-1" aria-labelledby="executeResultModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="executeResultModalLabel">执行结果</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="executeMessage"></div>
                    <pre id="executeLog" class="mt-3 p-3 bg-light"></pre>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除恢复任务 "<span id="deleteTaskName"></span>" 吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDelete">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.min.js"></script>
    <script th:src="@{/js/script.js}"></script>
    <script>
        $(document).ready(function() {
            // Upload backup file
            $('#uploadButton').click(function() {
                const formData = new FormData($('#uploadForm')[0]);
                
                if (!$('#backupFile').val() || !$('#targetDatabase').val() || !$('#taskName').val()) {
                    alert('请填写所有必填字段');
                    return;
                }
                
                // Show progress bar
                $('#uploadProgress').removeClass('d-none');
                
                $.ajax({
                    url: '/restore/save',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            $('#uploadBackupModal').modal('hide');
                            $('#successMessage').text('备份文件上传成功，恢复任务已创建');
                            $('#successAlert').show();
                            setTimeout(function() {
                                window.location.reload();
                            }, 1500);
                        } else {
                            $('#errorMessage').text('上传失败：' + response.message);
                            $('#errorAlert').show();
                        }
                    },
                    error: function() {
                        $('#errorMessage').text('上传失败：服务器错误');
                        $('#errorAlert').show();
                    },
                    xhr: function() {
                        const xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function(e) {
                            if (e.lengthComputable) {
                                const percent = Math.round((e.loaded / e.total) * 100);
                                $('#uploadProgress .progress-bar').css('width', percent + '%');
                            }
                        }, false);
                        return xhr;
                    }
                });
            });
            
            // Reset upload form when modal is closed
            $('#uploadBackupModal').on('hidden.bs.modal', function() {
                $('#uploadForm')[0].reset();
                $('#uploadProgress').addClass('d-none');
                $('#uploadProgress .progress-bar').css('width', '0%');
            });
            
            // Execute task
            $('.execute-btn').click(function() {
                const taskId = $(this).data('id');
                const taskName = $(this).data('name');
                
                $('#executeTaskName').text(taskName);
                $('#confirmExecute').data('id', taskId);
                $('#executeConfirmModal').modal('show');
            });
            
            $('#confirmExecute').click(function() {
                const taskId = $(this).data('id');
                const btn = $(this);
                
                btn.prop('disabled', true).text('执行中...');
                
                $.ajax({
                    url: '/restore/execute/' + taskId,
                    type: 'POST',
                    success: function(response) {
                        $('#executeConfirmModal').modal('hide');
                        
                        if (response.success) {
                            $('#executeMessage').html('<div class="alert alert-success">执行成功</div>');
                        } else {
                            $('#executeMessage').html('<div class="alert alert-danger">执行失败：' + response.message + '</div>');
                        }
                        
                        if (response.data && response.data.log) {
                            $('#executeLog').text(response.data.log);
                        } else {
                            $('#executeLog').text('无日志信息');
                        }
                        
                        $('#executeResultModal').modal('show');
                        btn.prop('disabled', false).text('确认执行');
                        
                        // Reload page after closing result modal
                        $('#executeResultModal').on('hidden.bs.modal', function() {
                            window.location.reload();
                        });
                    },
                    error: function() {
                        $('#executeConfirmModal').modal('hide');
                        $('#errorMessage').text('执行失败：服务器错误');
                        $('#errorAlert').show();
                        btn.prop('disabled', false).text('确认执行');
                    }
                });
            });
            
            // Delete task
            $('.delete-btn').click(function() {
                const taskId = $(this).data('id');
                const taskName = $(this).data('name');
                
                $('#deleteTaskName').text(taskName);
                $('#confirmDelete').data('id', taskId);
                $('#deleteConfirmModal').modal('show');
            });
            
            $('#confirmDelete').click(function() {
                const taskId = $(this).data('id');
                const btn = $(this);
                
                btn.prop('disabled', true).text('删除中...');
                
                $.ajax({
                    url: '/restore/' + taskId,
                    type: 'DELETE',
                    success: function(response) {
                        $('#deleteConfirmModal').modal('hide');
                        
                        if (response.success) {
                            $('#successMessage').text('删除成功');
                            $('#successAlert').show();
                            setTimeout(function() {
                                window.location.reload();
                            }, 1500);
                        } else {
                            $('#errorMessage').text('删除失败：' + response.message);
                            $('#errorAlert').show();
                        }
                        
                        btn.prop('disabled', false).text('确认删除');
                    },
                    error: function() {
                        $('#deleteConfirmModal').modal('hide');
                        $('#errorMessage').text('删除失败：服务器错误');
                        $('#errorAlert').show();
                        btn.prop('disabled', false).text('确认删除');
                    }
                });
            });
        });
    </script>
</body>
</html> 